/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.interceptor;

import org.apache.ibatis.aapl.annotation.EnhanceAfterField;
import org.apache.ibatis.aapl.annotation.strategy.EnhanceAfterFieldStrategy;
import org.apache.ibatis.aapl.reflect.MetaUtils;
import org.apache.ibatis.aapl.registry.MethodRegistry;
import org.apache.ibatis.aapl.registry.SqlMethod;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gu
 * @date 2020/4/7 14:14
 */
public class EnhanceAfterFieldProcessor implements ResultSetProcessor {

  private static Logger log = LoggerFactory.getLogger(EnhanceAfterFieldProcessor.class);

  private MethodRegistry registry = MethodRegistry.getMethodRegistry();

  private Map<Class<? extends EnhanceAfterFieldStrategy>, EnhanceAfterFieldStrategy> strategyMap = new HashMap<>(32);

  @Override
  public void process(ResultSetHandler handler, List<Object> objs) {
    if (objs == null || objs.size() == 0 || !(handler instanceof DefaultResultSetHandler)) {
      return;
    }
    doProcess(handler, objs);
  }

  private void doProcess(ResultSetHandler handler, List<Object> objs) {
    SqlMethod method = registry.getMethod(((DefaultResultSetHandler) handler));
    EnhanceAfterField annotation = method.getMethod().getAnnotation(EnhanceAfterField.class);
    if (annotation == null) {
      return;
    }
    String[] fields = annotation.fields();
    Class<? extends EnhanceAfterFieldStrategy>[] strategies = annotation.strategies();
    if (fields.length == 0) {
      return;
    }
    if (fields.length != strategies.length) {
      log.error("要增强的字段长度({})和对应的策略长度({})不一致！", fields.length, strategies.length);
      return;
    }
    for (Object obj : objs) {
      MetaObject metaObject = MetaUtils.getMetaObject(obj);
      for (int i = 0; i < fields.length; i++) {
        Class<? extends EnhanceAfterFieldStrategy> strategy = strategies[i];
        EnhanceAfterFieldStrategy realStrategy = strategyMap.computeIfAbsent(strategy, k -> {
          try {
            return strategy.newInstance();
          } catch (InstantiationException | IllegalAccessException e) {
            log.warn("请确保 {} 存在public且参数为空的构造函数！", strategy);
            return null;
          }
        });
        String field = fields[i];
        Object value = metaObject.getValue(field);
        metaObject.setValue(field, realStrategy.enhance(value));
      }
    }
  }
}
